package cn.stylefeng.guns.modular.constant.service.impl;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.constant.ConstantsHolderContext;
import cn.stylefeng.guns.modular.constant.entity.Constant;
import cn.stylefeng.guns.modular.constant.mapper.ConstantMapper;
import cn.stylefeng.guns.modular.constant.model.params.ConstantParam;
import cn.stylefeng.guns.modular.constant.model.result.ConstantResult;
import  cn.stylefeng.guns.modular.constant.service.ConstantService;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.List;

/**
 * <p>
 * 参数配置 服务实现类
 * </p>
 *
 * @author liuqiang
 * @since 2020-02-14
 */
@Service
public class ConstantServiceImpl extends ServiceImpl<ConstantMapper, Constant> implements ConstantService {

    @Override
    public void add(ConstantParam param){
        Constant entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(ConstantParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(ConstantParam param){
        Constant oldEntity = getOldEntity(param);
        Constant newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);

        ConstantsHolderContext.putConstant(newEntity.getCode(),newEntity.getValue());
        this.updateById(newEntity);
    }

    @Override
    public ConstantResult findBySpec(ConstantParam param){
        return null;
    }

    @Override
    public List<ConstantResult> findListBySpec(ConstantParam param){
        return null;
    }

    @Override
    public LayuiPageInfo findPageBySpec(ConstantParam param){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param);
        return LayuiPageFactory.createPageInfo(page);
    }

    private Serializable getKey(ConstantParam param){
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private Constant getOldEntity(ConstantParam param) {
        return this.getById(getKey(param));
    }

    private Constant getEntity(ConstantParam param) {
        Constant entity = new Constant();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

}
